package cn.tedu.boyou.website.interceptor;

import cn.tedu.boyou.cache.prefix.UserInfoKeyPrefix;
import cn.tedu.boyou.cache.service.IUserInfoRedisService;
import cn.tedu.boyou.member.domain.UserInfo;
import cn.tedu.boyou.website.annotation.RequireLogin;
import cn.tedu.boyou.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截校验
 * 继承：extends HandlerInterceptorAdapter
 * 实现：implements HandlerInterceptor
 *
 * HandlerInterceptorAdapter 适配器模式 JDK 1.8以前，接口没有默认实现，一些非关注的方法，需要重写，JDK1.8之后引入默认实现这种说法，
 *      实现接口时，选用需要关注的方法实现即可
 *
 */
public class CheckLoginInterceptor implements HandlerInterceptor{

    @Reference
    private IUserInfoRedisService userInfoRedisService;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录校验
        //获取浏览器传入的带有的cookie信息
        Cookie c = CookieUtil.getCookie(request, UserInfoKeyPrefix.TOKEN_COOKIE_NAME);

        UserInfo userInfo = null;
        if(c != null){
            //从redis中获取token 对应的用户对象
            userInfo = userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN,c.getValue());
        }

        //动态请求处理
        //HandlMethod ： 请求映射方法在springMVC中封装对象
        //而静态资源处理使用时，是另外一种处理对象
        if(handler instanceof HandlerMethod){

            //判断当前请求方法上是否贴有@RequireLogin登录拦截标签
            HandlerMethod hm = (HandlerMethod)handler;
            if(hm.hasMethodAnnotation(RequireLogin.class)){
                if(userInfo == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
